<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          <span>
            {{ page.total }}个员工

          </span>
        </template>
        <template #after>
          <el-button type="primary" size="mini" @click="exportExcel">导出</el-button>
          <el-button type="primary" size="mini" @click="$router.push('/import')">导入</el-button>
          <el-button type="primary" size="mini" @click="addemployee">新增员工</el-button>
        </template>
      </PageTools>
    </div>
    <el-card>
      <el-table v-loading="loading" border :data="list">
        <el-table-column label="序号" sortable="" type="index" />
        <el-table-column label="姓名" sortable="" prop="username" />
        <el-table-column label="头像" sortable="" prop="username" class="box">
          <template #default="{row}">
            <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto || ''" class="avatar" @click="showQrCode(row.staffPhoto)">
          </template>
        </el-table-column>
        <el-table-column label="工号" sortable="" prop="mobile" />
        <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
        <el-table-column label="部门" sortable="" prop="departmentName" />
        <el-table-column label="入职时间" sortable="" prop="correctionTime">
          <template #default="{row}">
            {{ row.correctionTime |formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="账户状态" sortable="" prop="enableState">
          <template #default="{row}">
            <el-switch
              :value="row.enableState ===1"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" sortable="" fixed="right" width="280">
          <template #default="{row}">
            <el-button type="text" size="small" @click="look(row.id)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="assignrole(row.id)">角色</el-button>
            <el-button type="text" :disabled="!checkPerm('bb')" size="small" @click="delEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination layout="prev, pager, next" :total="page.total" :page-size="page.size" :current-page="page.page" @current-change="handleCurrentChange" />
      </el-row>
      <!-- 弹出层组件 -->
      <AddEmployee :show-dialog.sync="showDialog" />
      <!-- 二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="avatarQRCode" />
        </el-row>
      </el-dialog>
      <!-- 权限弹窗 -->
      <assignRole ref="assignRole" :assignroledialog.sync="assignroledialog" :employee-id="employeeId" />
    </el-card>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees.js'
import { formatDate } from '@/filters/index.js'
import employees from '@/api/constant/employees.js'
import AddEmployee from '@/views/employees/components/add-employee.vue'
import assignRole from '@/views/employees/assign-role.vue'
// 引用二维码
import QRCode from 'qrcode'

export default {
  components: {
    AddEmployee,
    assignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1, // 当前页码
        size: 4,
        total: 0 // 总数
      },
      loading: false,
      showDialog: false,
      // 二维码
      showCodeDialog: false,
      // 权限弹窗
      assignroledialog: false,
      employeeId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    showQrCode(imgUrl) {
      if (imgUrl) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.avatarQRCode, imgUrl, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    look(id) {
      console.log(id)
      this.$router.push({
        path: `/employees/detail/${id}`
      })
    },
    assignrole(id) {
      this.assignroledialog = true
      this.employeeId = id
      this.$refs.assignRole.getUserDetail(id)
    },
    // 获取员工列表
    async getEmployeeList() {
      // 需要每次都把加载中的变量重新设为true，在发送网络请求完成时再设回false，不然只触发一次
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows.map((ele) => {
        const formOfEmployment = Math.ceil(Math.random() * 2)
        const enableState = Math.ceil(Math.random() * 2)
        return { ...ele, enableState, formOfEmployment }
      })
      this.page.total = total
      this.loading = false
    },
    // 分页功能
    handleCurrentChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    // 利用格式化处理聘用形式
    formatEmployment(row, column, cellValue, index) {
      const ojb = employees.hireType.find((ele) => ele.id === cellValue)
      return ojb.value
    },
    // enableState(row, column, cellValue, index) {
    //   const ojb = employees.hireType.find((ele) => ele.id === cellValue)
    //   return ojb.value
    // },
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除员工？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delEmployee(id)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    addemployee() {
      this.showDialog = true
    },
    // 导出
    async  exportExcel() {
      const zidian = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const header = Object.keys(zidian)
      const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
      const data = rows.map((user) => {
        return this.arrFn(user, zidian)
      })
      const { export_json_to_excel } = await import('@/vendor/Export2Excel.js')
      export_json_to_excel({
        header,
        data
      })
    },
    arrFn(user, zidian) {
      const arr = []
      // for (const key1 in user) {
      //   for (const key2 in zidian) {
      //     if (zidian[key2] === key1) {
      //       arr.push(user[key1])
      //     }
      //   }
      // }
      for (const key in zidian) {
        const enkey = zidian[key]
        let value = user[enkey]
        // 如果是聘用形式
        if (enkey === 'formOfEmployment') {
          const ojb = employees.hireType.find(item => item.id === value)
          // 如果ojb存在则使用ojb的value（正式或未正式），如果不存在则为null
          value = ojb ? ojb.value : '未知形式'
        }
        if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
          value = formatDate(value)
        }
        arr.push(value)
      }
      return arr
    }

  }
}
</script>

<style lang="scss" scoped>

  .avatar{
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
</style>
